package com.xqboss.apps.listener;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.xqboss.apps.constant.LockKey;
import com.xqboss.apps.constant.RedisKey;
import com.xqboss.apps.domain.punch.PunchUserConfig;
import com.xqboss.apps.enums.mq.AppMqDelayEnum;
import com.xqboss.apps.enums.sys.PushJumpEnum;
import com.xqboss.apps.service.msg.PushService;
import com.xqboss.apps.service.punch.PunchUserConfigService;
import com.xqboss.common.core.mq.MqEnum;
import com.xqboss.common.core.mq.MqListener;
import com.xqboss.common.core.redis.RedisCache;
import com.xqboss.common.core.redis.lock.LockValue;
import com.xqboss.common.core.redis.lock.RedisLock;
import org.apache.rocketmq.client.apis.consumer.ConsumeResult;
import org.apache.rocketmq.client.apis.message.MessageView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *     用户打卡倒计时监听器
 * </p>
 * @author Trent
 * @date 2023/9/7
 */
@Component
public class UserPunchCountdownListener extends MqListener {

    @Lazy
    @Autowired
    private PunchUserConfigService userConfigService;
    @Lazy
    @Autowired
    private PushService pushService;

    @Override
    public MqEnum getEnum() {
        return AppMqDelayEnum.PUNCH_COUNTDOWN;
    }

    @Override
    public ConsumeResult solve(MessageView message) {
        String value = StandardCharsets.UTF_8.decode(message.getBody()).toString();
        long id = Long.parseLong(value);
        // 这个ID是用户打卡配置ID
        PunchUserConfig config = userConfigService.getById(id);
        if(config != null && config.getNextPunchTime() != null){
            // 判断下次打卡时间确实在2分钟之内
            long between = LocalDateTimeUtil.between(LocalDateTime.now(), config.getNextPunchTime(), ChronoUnit.SECONDS);
            if(between > 0 && between < 60 * 2){
                // 不在这个周期内，说明可能修改了打卡规则
                pushService.pushPunchMsg(config.getUserId());
            }
        }
        return ConsumeResult.SUCCESS;
    }
}
